package cn.zmit.kuxi.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.adapter.ExpressRecyAdapter;
import cn.zmit.kuxi.adapter.ExpressRecyAdapter.OnItemClickListener;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.entity.ExpressEntity;
import cn.zmit.kuxi.utils.HttpClientUtils;
import cn.zmit.kuxi.widget.PtrHeader;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

public class ExpressActivity extends BaseActivity {
	private RecyclerView lv_express_item;
	private List<ExpressEntity> mExpressList = new ArrayList<ExpressEntity>();
	private String user_id;
	private ExpressRecyAdapter adapter;
	private LinearLayoutManager mLayoutManager;
	private int mPage = 1;
	private static int LOAD_STATE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_express);
		ViewUtils.inject(this);
		setTitleView("快递查询", true);
		initView();
		initPtr();
		initListener();
	}

	private void initListener() {
		lv_express_item
				.setOnScrollListener(new RecyclerView.OnScrollListener() {
					@Override
					public void onScrolled(RecyclerView recyclerView, int dx,
							int dy) {
						super.onScrolled(recyclerView, dx, dy);

					}

					@Override
					public void onScrollStateChanged(RecyclerView recyclerView,
							int newState) {
						super.onScrollStateChanged(recyclerView, newState);
						if (mLayoutManager.findLastVisibleItemPosition() == 8 * mPage - 1
								&& newState == RecyclerView.SCROLL_STATE_IDLE) {
							mPage++;
							// tv_footerview.setVisibility(View.VISIBLE);
//							LOAD_STATE = 1;
							initData();
						}
					}
				});

	}

	private void initView() {
		lv_express_item = (RecyclerView) findViewById(R.id.lv_express_item);
		lv_express_item.setHasFixedSize(true);
		mLayoutManager = new LinearLayoutManager(ExpressActivity.this);
		lv_express_item.setLayoutManager(mLayoutManager);// 普通设置

		tv_footerview = (TextView) findViewById(R.id.tv_footerview);
		user_id = PreferenceHelper.readString(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
	}

	private void initData() {
		RequestParams params = new RequestParams();
		params.add("user_id", user_id);
		HttpClientUtils.getInstance().post(Url.EXPRESS + mPage, params,
				new MyResponseHandler());
	}

	class MyResponseHandler extends AsyncHttpResponseHandler {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Toast.makeText(context, "网络错误", 0).show();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String response = new String(arg2);
			if (response != null) {
				try {
					JSONObject root = new JSONObject(response);
					JSONArray arr = root.getJSONArray("express");
					if (arr != null && arr.length() > 0) {
						for (int i = 0; i < arr.length(); i++) {
							JSONObject obj = arr.getJSONObject(i);
							String phase = obj.getString("phase");
							String name = obj.getString("name");
							String deliver = obj.getString("deliver");
							String time = obj.getString("deliverOn");
							String pic = obj.getString("pic");
							ExpressEntity entity = new ExpressEntity(phase,
									name, deliver, time, pic);

							mExpressList.add(entity);
						}
					} else {
						tv_footerview.setVisibility(View.VISIBLE);
						tv_footerview.setText("数据加载完毕");
					}
					if (adapter == null) {
						adapter = new ExpressRecyAdapter(mExpressList,
								ExpressActivity.this);
						adapter.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(View view, int position) {
								// Toast.makeText(context, "click" + position,
								// 0)
								// .show();
							}
						});
						lv_express_item.setAdapter(adapter);
					} else {
						adapter.notifyDataSetChanged();
					}
					// tv_footerview.setVisibility(View.INVISIBLE);
					ptr_view.refreshComplete();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		}
	}

	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;
	private TextView tv_footerview;

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {
						mPage = 1;
						mExpressList.clear();
						initData();
					}
				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						lv_express_item, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}
}
